from fastapi import APIRouter, Depends, HTTPException

from core.crud import user_detail_by_id, user_save, user_change_address0
from core.dependencies import common_dependencies, get_db, log_route
from core.schemas import UserCreate, ResponseModel
from sqlalchemy.orm import Session

router = APIRouter(
    prefix="/user",
    tags=["用户"],
    responses={404: {"description": "Not found"}},
)


@router.get("/user-detail")
async def user_detail(common: dict = Depends(common_dependencies), _=Depends(log_route)):
    user = user_detail_by_id(common["db"], common["user_id"])
    if user:
        return ResponseModel(data=user.to_dict(), code="200", message="success")
    else:
        return ResponseModel(data=None, code="404", message="User not found")


@router.post("/user-create")
async def user_create(user: UserCreate, db: Session = Depends(get_db), _=Depends(log_route)):
    user.password = user.password  # 这里会调用我们在User模型中定义的setter方法
    created_user = user_save(db, user)
    if created_user:
        return ResponseModel(data=created_user.to_dict(), code="200", message="success")
    else:
        return ResponseModel(data=None, code="400", message="User creation failed")


@router.post("/user-change-address")
async def user_change_address(address: str, common: dict = Depends(common_dependencies), _=Depends(log_route)):
    user = user_detail_by_id(common["db"], common["user_id"])
    if user is None:
        return ResponseModel(data=None, code="404", message="User not found")
    updated_user = user_change_address0(common["db"], user, address)
    if updated_user:
        return ResponseModel(data=updated_user.to_dict(), code="200", message="success")
    else:
        return ResponseModel(data=None, code="400", message="User address update failed")
